import axios from 'axios'
import store from '@/store'
import { Toast } from 'vant'
import { getRequestId } from '@/utils/index'
// 处理登录问题
import alert from '@/utils/alert'
import router from '@/router'


// create an axios instance
export const baseURL = process.env.NODE_ENV === 'development' ? '' : `${window.location.origin}`
const service = axios.create({
  baseURL,
  // withCredentials: true, // send cookies when cross-domain requests
  timeout: 50000 // request timeout
})
// request interceptor
service.interceptors.request.use(
  config => {
    config.headers = {
      'Authorization': store.getters.userInfo.token,
    }
    return config
  },
  error => {
    console.log(error) // for debug
    return Promise.reject(error)
  }
)
// response interceptor
service.interceptors.response.use(
  /**
   * If you want to get http information such as headers or status
   * Please return  response => response
   */

  /**
   * Determine the request status by custom code
   * Here is just an example
   * You can also judge the status by HTTP Status Code
   */
  response => {
    const res = response.data
    // if the custom code is not 20000, it is judged as an error.
    if (res.code !== 200) {
      if (!response.config.ignoreError) {
        Toast(res.message || 'Error')
      }

      // 401 Unauthorized  403 Forbidden
      if (res.code === 403 || res.code === 401) {
        store.dispatch('user/resetToken')
      }
      // return Promise.reject(new Error(res.msg || 'Error'))
    }
    return res
  },
  error => {
    if (error.response.status === 401) {
      // token失效
      store.dispatch('user/resetToken')
      Toast('token失效')
    } else {
      Toast(error.message)
      return Promise.reject(error)
    }
  }
)

export default service.request
